﻿using gt.framework.Log;
using gt.webapi.core.Extensions;
using Newtonsoft.Json;
using System;
using System.Net.Http;

namespace gt.webapi.core.Logging
{
    public class ApiLogger
    {
        private ILogWrapper m_infoLogger = null;
        private ILogWrapper m_errorLogger = null;

        public ApiLogger(ILogWrapper infoLogger, ILogWrapper errorLogger)
        {
            this.m_infoLogger = infoLogger ?? throw new ArgumentNullException("infoLogger");
            this.m_errorLogger = errorLogger ?? throw new ArgumentNullException("errorLogger");
        }

        public virtual void Info(HttpRequestMessage requestMessage, HttpResponseMessage responsMessage)
        {
            var log = BuildLog(requestMessage, responsMessage);
            try
            {
                m_infoLogger.Info(JsonConvert.SerializeObject(log));
            }
            catch { }
        }

        public virtual void Error(string requestId, string message)
        {
            string errorMsg = string.Format("request:{0},error:{1}", requestId, message);
            try
            {
                m_errorLogger.Error(errorMsg);
            }
            catch { }
        }
        public virtual void Error(string requestId, Exception ex)
        {
            try
            {
                m_errorLogger.Error(requestId, ex);
            }
            catch { }
        }

        protected virtual LogEntry BuildLog(HttpRequestMessage requestMessage, HttpResponseMessage responsMessage)
        {
            return new LogEntry()
            {
                RequestId = requestMessage.GetRequestId(),
                RequestUrl = requestMessage.RequestUri.AbsoluteUri,
                ControllerAction = requestMessage.GetControllerActionPath(),
                StatusCode = (int)responsMessage.StatusCode,
                UserAgent = requestMessage.Headers.UserAgent.ToString(),
                Appkey = requestMessage.GetAppKey(),
                UrlParam = requestMessage.GetUrlParam(),
                Request = requestMessage.GetRequestString(),
                Response = responsMessage.Content == null ? string.Empty : responsMessage.Content.ReadAsStringAsync().Result,
                ClientIp = requestMessage.GetClientRealIp(),
                ServerIp = framework.Util.HttpClientUtils.GetLocalIp(),
                Duration = requestMessage.GetDurationTime()
            };
        }
    }
}
